<script setup>
import { useUserStore } from '@/stores/user'
import { ref, onMounted, nextTick, onBeforeUnmount } from 'vue'
import * as echarts from 'echarts'
import { getStudentClassDataApi } from '@/api/job'
import { getAllMajorListApi, getClassApi, getCollegeApi } from '@/api/baseData'

const userStore = useUserStore()
// 选择器的值

const classValue = userStore.userInfo.identity == '管理员' ? '全部' : userStore.userInfo.class[0]
const selectedClass = ref(classValue)
const selectMajor = ref(null)
const selectCollege = ref(null)
// 选择器的选项
const classes = ref(userStore.userInfo.class)
const majors = ref([])
const colleges = ref([])
// 获取专业和学院
const getMajorsAndColleges = async () => {
  if (userStore.userInfo.identity == '管理员' && userStore.userInfo.college != '*') {
    colleges.value = [userStore.userInfo.college]
    console.log('colleges',colleges.value);
    ('colleges',colleges.value)
    const res2 = await getAllMajorListApi({ college: userStore.userInfo.college })
    majors.value = res2.data.map((item) => item.major)
    console.log(majors.value);
    
    const res=await getClassApi({ college: userStore.userInfo.college })
    classes.value = res.data.map((item) => item.class)
    return
  }

  const res = await getCollegeApi()
  colleges.value = res.data.map((item) => item.college)
  const res2 = await getAllMajorListApi()
  majors.value = res2.data.map((item) => item.major)
  const res3=await getClassApi()

  classes.value = res3.data.map((item) => item.class)

}
getMajorsAndColleges()

const internshipChartRef = ref(null)
const employmentChartRef = ref(null)
const statisticsData = ref({
  totalStudents: 30,
  internshipRate: '66.7%',
  employmentRate: '40%'
})

// 模拟数据
const analysisData = ref({
  internshipStatus: {
    已实习: 15,
    未实习: 10
  },
  employmentStatus: {
    已就业: 12,
    未就业: 13
  }
})

// 添加加载状态
const loading = ref(false)

const initCharts = () => {
  // 使用 setTimeout 确保 DOM 完全渲染并且有正确的尺寸
  setTimeout(() => {
    const internshipDom = document.getElementById('internshipChart')
    const employmentDom = document.getElementById('employmentChart')

    if (internshipDom && employmentDom) {
      // 确保容器有明确的尺寸
      internshipDom.style.width = '100%'
      internshipDom.style.height = '270px'
      employmentDom.style.width = '100%'
      employmentDom.style.height = '270px'

      // 初始化图表
      internshipChartRef.value = echarts.init(internshipDom)
      employmentChartRef.value = echarts.init(employmentDom)
      updateCharts()
    }
  }, 0)
}

const updateCharts = async () => {
  loading.value = true
  let params = null
  userStore.userInfo.identity == '管理员'
    ? (params = {
        selectClass: selectedClass.value,
        selectMajor: selectMajor.value,
        selectCollege: selectCollege.value
      })
    : (params = { selectClass: selectedClass.value })
  try {
    const res = await getStudentClassDataApi(params)
    statisticsData.value.totalStudents = res.studentTotal
    statisticsData.value.internshipRate =
      res.studentTotal === 0
        ? '0%'
        : ((res.practiceTotal / res.studentTotal) * 100).toFixed(2) + '%'
    statisticsData.value.employmentRate =
      res.studentTotal === 0
        ? '0%'
        : ((res.employmentTotal / res.studentTotal) * 100).toFixed(2) + '%'
    // 分配数据
    analysisData.value.internshipStatus.已实习 = res.practiceTotal
    analysisData.value.internshipStatus.未实习 = res.studentTotal - res.practiceTotal
    analysisData.value.employmentStatus.已就业 = res.employmentTotal
    analysisData.value.employmentStatus.未就业 = res.studentTotal - res.employmentTotal
    // 更新饼图配置
    const chartColors = ['#409EFF', '#67C23A', '#E6A23C', '#F56C6C', '#909399']

    const internshipOption = {
      tooltip: {
        trigger: 'item',
        formatter: '{b}: {c} ({d}%)'
      },
      legend: {
        orient: 'vertical',
        left: '5%',
        top: 'middle'
      },
      series: [
        {
          name: '实习状态',
          type: 'pie',
          radius: ['20%', '50%'],
          itemStyle: {
            borderRadius: 10,
            borderColor: '#fff',
            borderWidth: 3,
            shadowBlur: 10,
            shadowColor: 'rgba(0, 0, 0, 0.2)'
          },
          label: {
            show: true,
            position: 'outside',
            formatter: '{b}: {d}%'
          },
          emphasis: {
            label: {
              show: true,
              fontSize: 16,
              fontWeight: 'bold'
            }
          },
          data: Object.entries(analysisData.value.internshipStatus).map(([name, value]) => ({
            name,
            value
          })),
          color: chartColors
        }
      ]
    }

    const employmentOption = {
      tooltip: {
        trigger: 'item',
        formatter: '{b}: {c} ({d}%)'
      },
      legend: {
        orient: 'vertical',
        left: '5%',
        top: 'middle'
      },
      series: [
        {
          name: '就业状态',
          type: 'pie',
          radius: ['20%', '50%'],
          center: ['60%', '50%'],
          avoidLabelOverlap: false,
          itemStyle: {
            borderRadius: 10,
            borderColor: '#fff',
            borderWidth: 2,
            shadowBlur: 10,
            shadowColor: 'rgba(0, 0, 0, 0.2)'
          },
          label: {
            show: true,
            position: 'outside',
            formatter: '{b}: {d}%'
          },
          emphasis: {
            label: {
              show: true,
              fontSize: 16,
              fontWeight: 'bold'
            }
          },
          data: Object.entries(analysisData.value.employmentStatus).map(([name, value]) => ({
            name,
            value
          })),
          color: chartColors
        }
      ]
    }

    internshipChartRef.value.setOption(internshipOption)
    employmentChartRef.value.setOption(employmentOption)
  } catch (error) {
    console.error('获取数据失败:', error)
  } finally {
    loading.value = false
  }
}

// 添加销毁图表的逻辑
onBeforeUnmount(() => {
  internshipChartRef.value?.dispose()
  employmentChartRef.value?.dispose()
  window.removeEventListener('resize', handleResize)
})

// 抽取resize处理函数
const handleResize = () => {
  internshipChartRef.value?.resize()
  employmentChartRef.value?.resize()
}
function handleCollegeChange(newCollege) {
  console.log(newCollege)
  selectMajor.value = null
  selectedClass.value = null
  selectCollege.value = newCollege
  updateCharts()
}
function handleMajorChange(newMajor) {
  console.log(newMajor)
  selectCollege.value = null
  selectedClass.value = null
  selectMajor.value = newMajor
  updateCharts()
}
const handleClassChange = (newClass) => {
  console.log(newClass)
  selectCollege.value = null
  selectMajor.value = null

  selectedClass.value = newClass
  // 这里应该调用API获取新的数据
  updateCharts()
}

onMounted(() => {
  initCharts()
  window.addEventListener('resize', handleResize)
  if (classes.value == '*') {
    classes.value = ['全部']
  }
})

// 添加数据卡片的图标配置
const cardIcons = {
  totalStudents: 'User',
  internshipRate: 'Briefcase',
  employmentRate: 'GraduationCap',
  averageSalary: 'Money'
}
</script>

<template>
  <div class="analysis-container">
    <!-- 页面标题部分 -->
    <div class="page-title">
      <h1 v-if="userStore.userInfo.identity == '管理员' && selectCollege">{{ selectCollege }}</h1>
      <h1 v-if="userStore.userInfo.identity == '管理员' && selectMajor">{{ selectMajor }}</h1>
      <h1 v-if="selectedClass">{{ selectedClass }}</h1>
      <el-select
        v-model="selectCollege"
        v-if="userStore.userInfo.identity == '管理员'"
        @change="handleCollegeChange"
        placeholder="选择学院"
        class="class-select"
      >
        <el-option v-for="cls in colleges" :key="cls" :label="cls" :value="cls" />
      </el-select>
      <el-select
        v-model="selectMajor"
        v-if="userStore.userInfo.identity == '管理员'"
        @change="handleMajorChange"
        placeholder="选择专业"
        class="class-select"
      >
        <el-option v-for="cls in majors" :key="cls" :label="cls" :value="cls" />
      </el-select>
      <el-select
        v-model="selectedClass"
        @change="handleClassChange"
        placeholder="选择班级"
        class="class-select"
      >
        <el-option v-for="cls in classes" :key="cls" :label="cls" :value="cls" />
      </el-select>
    </div>

    <!-- 内容部分 -->
    <div class="content-wrapper" v-loading="loading">
      <!-- 统计卡片 -->
      <div class="statistics-cards">
        <el-card v-for="(value, key) in statisticsData" :key="key" class="stat-card">
          <template #header>
            <div class="card-header">
              <el-icon class="icon"><component :is="cardIcons[key]" /></el-icon>
              <span>{{
                {
                  totalStudents: '总人数',
                  internshipRate: '实习率',
                  employmentRate: '就业率'
                }[key]
              }}</span>
            </div>
          </template>
          <div class="card-value">
            <span class="number">{{ value }}</span>
            <el-icon v-if="key === 'employmentRate'" class="status-icon">
              <Histogram />
            </el-icon>
            <div class="decoration-bar"></div>
          </div>
        </el-card>
      </div>

      <!-- 图表部分 -->
      <div class="charts-container">
        <el-card class="chart-card">
          <div class="chart-header">
            <el-icon><DataLine /></el-icon>
            <span>实习情况分布</span>
          </div>
          <div id="internshipChart" class="chart"></div>
        </el-card>
        <el-card class="chart-card">
          <div class="chart-header">
            <el-icon><PieChart /></el-icon>
            <span>就业情况分布</span>
          </div>
          <div id="employmentChart" class="chart"></div>
        </el-card>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.analysis-container {
  background-color: #f5f7fa;
  min-height: calc(100vh - 60px);
  padding: 20px;
  display: flex;
  flex-direction: column;
  gap: 24px;

  .page-title {
    background: #409eff;
    padding: 20px 24px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

    h1 {
      margin: 0;
      color: #fff;
      font-size: 24px;
      font-weight: 500;
      display: flex;
      align-items: center;
      gap: 12px;

      &::before {
        content: '';
        width: 4px;
        height: 24px;
        background: #fff;
        border-radius: 2px;
      }
    }

    .class-select {
      width: 220px;

      :deep(.el-input__wrapper) {
        background: rgba(255, 255, 255, 0.9);
      }

      &:hover {
        :deep(.el-input__wrapper) {
          background: #fff;
        }
      }
    }
  }

  .content-wrapper {
    display: flex;
    flex-direction: column;
    gap: 24px;

    .statistics-cards {
      display: flex;
      gap: 80px;
      margin: 30px 0;

      .stat-card {
        flex: 1;
        transition: all 0.3s ease;
        border: none;

        &:hover {
          transform: translateX(5px);
          box-shadow: 0 8px 20px rgba(0, 0, 0, 0.1);
        }

        .card-header {
          display: flex;
          align-items: center;
          gap: 8px;
          font-size: 14px;
          color: #606266;

          .icon {
            font-size: 18px;
            color: #409eff;
          }
        }

        .card-value {
          position: relative;
          padding: 10px 0;

          .number {
            font-size: 24px;
            font-weight: bold;
            color: #303133;
            display: block;
            text-align: center;
          }

          .status-icon {
            position: absolute;
            right: 20px;
            top: 50%;
            transform: translateY(-50%);
            font-size: 20px;
            color: #409eff;
          }

          .decoration-bar {
            position: absolute;
            bottom: 0;
            left: 50%;
            transform: translateX(-50%);
            width: 40px;
            height: 3px;
            background: linear-gradient(90deg, #409eff 0%, rgba(64, 158, 255, 0.2) 100%);
            border-radius: 1.5px;
          }
        }
      }
    }

    .charts-container {
      display: flex;
      gap: 24px;

      .chart-card {
        width: 50%;
        background: #fff;
        border-radius: 8px;
        box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
        transition: all 0.3s ease;
        border: none;
        height: 300px;

        &:hover {
          transform: translateY(-5px);
          box-shadow: 0 8px 20px rgba(0, 0, 0, 0.1);
        }

        .chart-header {
          display: flex;
          align-items: center;
          gap: 8px;
          padding: 16px;
          font-size: 16px;
          color: #303133;
          border-bottom: 1px solid #f0f0f0;

          .el-icon {
            color: #409eff;
          }
        }

        .chart {
          height: 270px;
          width: 100%;
        }
      }
    }
  }
}

// 响应式布局
@media screen and (max-width: 768px) {
  .analysis-container {
    padding: 16px;

    .page-title {
      flex-direction: column;
      gap: 16px;

      .class-select {
        width: 100%;
      }
    }

    .content-wrapper {
      .statistics-cards {
        flex-direction: column;

        .stat-card {
          width: 100%;
        }
      }
    }
  }
}
</style>
